import axios from 'axios'
import type { Meeting, Transcript, Minutes } from '@/types'

const API_BASE_URL = 'http://localhost:8000'

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 600000, // 10分钟超时，适应长时间推理
  headers: {
    'Content-Type': 'application/json',
  },
})

// 响应拦截器
api.interceptors.response.use(
  (response) => response,
  (error) => {
    console.error('API Error:', error)
    throw error
  }
)

// 健康检查
export const healthCheck = async () => {
  const response = await api.get('/api/v1/health')
  return response.data
}

// 会议管理
export const createMeeting = async (data: { title: string; description?: string }) => {
  const response = await api.post('/api/v1/meetings', data)
  return response.data
}

export const getMeetings = async () => {
  const response = await api.get('/api/v1/meetings')
  return response.data
}

export const getMeeting = async (id: string) => {
  const response = await api.get(`/api/v1/meetings/${id}`)
  return response.data
}

export const deleteMeeting = async (id: string) => {
  await api.delete(`/api/v1/meetings/${id}`)
}

// 音频转录
export const transcribeAudio = async (
  audioFile: File,
  meetingId?: string,
  onProgress?: (progress: number) => void
) => {
  const formData = new FormData()
  formData.append('file', audioFile)
  if (meetingId) {
    formData.append('meeting_id', meetingId)
  }

  const response = await api.post('/api/v1/audio/transcribe', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    timeout: 600000, // 10分钟转录超时
    onUploadProgress: (progressEvent) => {
      if (onProgress && progressEvent.total) {
        const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        onProgress(Math.min(progress, 90)) // 上传最多显示90%
      }
    },
  })

  // 转录完成，显示100%
  if (onProgress) onProgress(100)

  return response.data
}

// 纪要管理
export const generateMinutes = async (
  meetingId: string,
  template?: string,
  onProgress?: (progress: number) => void
) => {
  // 模拟进度更新，因为后端不支持真正的进度回调
  const simulateProgress = () => {
    if (onProgress) {
      let progress = 10
      const interval = setInterval(() => {
        progress += Math.random() * 15 // 随机增长
        if (progress >= 95) {
          onProgress(95)
          clearInterval(interval)
        } else {
          onProgress(Math.floor(progress))
        }
      }, 2000) // 每2秒更新一次
    }
  }

  simulateProgress()

  const response = await api.post('/api/v1/minutes/generate', {
    meeting_id: meetingId,
    template,
  }, {
    timeout: 600000, // 10分钟纪要生成超时
  })

  // 完成后显示100%
  if (onProgress) onProgress(100)

  return response.data
}

export const getMinutes = async (meetingId: string) => {
  const response = await api.get(`/api/v1/minutes/${meetingId}`)
  return response.data
}

export const updateMinutes = async (meetingId: string, content: string) => {
  const response = await api.put(`/api/v1/minutes/${meetingId}`, {
    content,
  })
  return response.data
}

export default api